<?php

namespace App\Models;

use GuzzleHttp\Client;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Model;

class LiveMeetingRoomUser extends Model
{
	
    use SoftDeletes;

    protected $table = 'live_meeting_room_user';

    /**
     * 定义主键
     * @var string
     */
    protected $primaryKey = 'id';

    /**
     * 禁止批量赋值的字段
     *
     * @var array
     */
    protected $guarded = ['id','created_at','deleted_at'];

    /**
     * 软删除应该被调整为日期的属性
     * [$dates description]
     * @var [type]
     */
    protected $dates=[
        'created_at', 'updated_at','deleted_at'
    ];


    protected $appends = ['user_name'];

    /**
     * 关联
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function user_info()
    {
        return $this->hasOne('\App\Models\User', 'id', 'user_id');
    }

    public function getUserNameAttribute()
    {
        $user = User::find($this -> user_id);
        return $user ? ($user -> real_name ?: $user -> user_name) : '';
    }


    // 核验 token是否有效
    public static function checkToken($room_id, $user_no, $token)
    {

        $res = self::where('room_user_no',$user_no) -> where('room_no', $room_id) -> first();

        if($res){

            if($res -> token == $token && $res -> token_expiration_time > date('Y-m-d H:i:s')){
                return $res -> token;
            }else{

                $token = get_zego_token($room_id, $user_no);
                $res -> token                 = $token;
                $res -> token_expiration_time = date('Y-m-d H:i:s',(time() + 3600));
                $liveMeetingRoomUser = $res -> save();

                if($liveMeetingRoomUser){
                    return $token;
                }else{
                    return false;
                }
            }

        }else{
            return false;
        }
    }

    /**  房间踢人
     * @param $roomId   string
     * @param $user_ids array
     */
    public static function roomGetOut($roomId, $user_ids){

        $http = new Client();


        $url = "https://rtc-api.zego.im/?Action=KickoutUser";
        $param = "&RoomId=".$roomId;
        foreach($user_ids as $v){
            $param .= "&UserId[]=".$v;
        }


        // $url 与参数组合
        $common_param = LiveMeetingRoom::commonParam();
        $url = $url.$param.'&'.$common_param;
        $res = $http -> get($url);


        $result = json_decode($res->getBody()->getContents(),true);
        if($result['Message'] == 'success'){
            return true;   //$result['Data'];
        }

        return false;
    }
    
}
